package com.ifonly.activerecord.sql.config;

import com.google.common.io.Resources;
import com.ifonly.config.Configuration;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.File;
import java.io.FileFilter;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author <a href="mailto:ifonlymaster@163.com">ifonly</a>
 * @version 1.0 2015-12-23 17:20
 * @since JDK 1.6
 */
public class Sql {

    private static Configuration configuration = Configuration.getInstance();

    private static Map<String, String> sqlMapping = new HashMap<String, String>();

    public static void init() {
        sqlMapping.clear();
        String regex = configuration.getSqlMapper();
        Pattern p = Pattern.compile(regex);
        final URL resource = Resources.getResource("");
        if (resource == null) {
            throw new NullPointerException("the resources is null.");
        }

        File file = new File(resource.getFile());
        List<File> files = mapperFiles(file, file.getAbsolutePath(), p);
        initSqlMapping(files);
    }

    private static void initSqlMapping(List<File> files) {
        try {
            JAXBContext cxt = JAXBContext.newInstance(Items.class);
            Unmarshaller unmarshaller = cxt.createUnmarshaller();

            for (File file : files) {
                Items items = (Items) unmarshaller.unmarshal(file);
                String itemsId = items.id;
                List<Item> itemList = items.items;
                for (Item s : itemList) {
                    String sqlId = s.id;
                    String value = s.value.trim();
                    String key = itemsId + "." + sqlId;
                    if (sqlMapping.get(key) != null) {
                        throw new RuntimeException("The Key[" + key + "] exist");
                    }

                    sqlMapping.put(key, value);
                }
            }
        } catch (JAXBException e) {
            e.printStackTrace();
            throw new RuntimeException("Parse mapper file [" + files + "] failed", e);
        }
    }

    static List<File> mapperFiles(final File file, final String root, final Pattern pattern) {
        List<File> list = new ArrayList<File>();

        File[] files = file.listFiles(new FileFilter() {
            public boolean accept(File pathname) {
                if (pathname.isDirectory()) {
                    return true;
                }
                String path = pathname.getAbsolutePath();
                if (!path.endsWith(".xml")) {
                    return false;
                }
                path = path.replace(root, "");
                Matcher matcher = pattern.matcher(path);
                return matcher.find();
            }
        });

        for (File f : files) {
            if (f.isDirectory()) {
                list.addAll(mapperFiles(f, root,  pattern));
            } else {
                list.add(f);
            }
        }
        return list;
    }

    public static String get(String key) {
        String sql = sqlMapping.get(key);
        if (sql != null) {
            return sql.trim();
        }
        return null;
    }

}
